package com.goldcn.b2b.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.goldcn.b2b.dao.ClassifyDiscountDetailMapper;
import com.goldcn.b2b.dao.ClassifyDiscountGroupMapper;
import com.goldcn.b2b.dto.ClassifyDiscountGroupDto;
import com.goldcn.b2b.dto.GoodsQueryDto;
import com.goldcn.b2b.model.ClassifyDiscountDetail;
import com.goldcn.b2b.model.ClassifyDiscountGroup;
import com.goldcn.common.BigDecimalUtil;
import com.goldcn.common.DataUtils;
import com.goldcn.common.HttpUtil;
import com.goldcn.common.JsonUtil;
import com.goldcn.common.exception.ServiceException;
import com.goldcn.common.model.DataResult;
import com.goldcn.common.util.IdGen;
import com.goldcn.config.Constants;
import com.goldcn.config.ProConstants;
import com.goldcn.goods.dao.GoodsInfoMapper;
import com.goldcn.goods.dao.GoodsSkuMapper;
import com.goldcn.goods.dto.QueryGoodsSkuRateDto;
import com.goldcn.goods.model.GoodsInfo;
import com.goldcn.goods.model.GoodsSku;
import com.goldcn.goods.service.GoodsService;
import com.goldcn.interceptor.SystemContext;
import com.goldcn.order.dto.UserIDGoodsByDto;
import com.google.common.base.Objects;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.primitives.Longs;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/9/25.
 */
@Service
@Transactional
@ConfigurationProperties("bank")
public class ClassifyDiscountService {

    //云管控按品类查子类
    private String classifySearchByIdUrl;
    private String classifyUrl;


    @Autowired
    ClassifyDiscountGroupMapper classifyDiscountGroupMapper;
    @Autowired
    ClassifyDiscountDetailMapper classifyDiscountDetailMapper;
    @Autowired
    GoodsInfoMapper goodsInfoMapper;
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    RestTemplate rest;
    @Autowired
    GoodsService goodsService;
    @Autowired
    GoodsSkuMapper goodsSkuMapper;

    private static Logger logger = LoggerFactory.getLogger(ClassifyDiscountService.class);

    /**
     * 新增或修改分组
     * @param dto
     * @return
     */
    public Object addClassifyDiscountGroup(ClassifyDiscountGroupDto dto) {
        validateGroupName(dto);
        dto.setCompanyID(SystemContext.getCompanyID());
        if (dto.getGroupID() == null || dto.getGroupID() == 0) {
            dto.setGroupID(IdGen.get().nextId());
            dto.setAddTime(System.currentTimeMillis());
            List<ClassifyDiscountDetail> details = dto.getDetails();
            //StringBuffer sb = new StringBuffer();
            if (CollectionUtils.isNotEmpty(details)) {
                for (ClassifyDiscountDetail classifyDiscountDetail : details) {
                    classifyDiscountDetail.setId(IdGen.get().nextId());
                    classifyDiscountDetail.setGroupID(dto.getGroupID());
                    classifyDiscountDetail.setCompanyID(SystemContext.getCompanyID());
                }
                classifyDiscountDetailMapper.batchInsert(details);
            }
            classifyDiscountGroupMapper.insertSelective(dto);
        } else {
            List<ClassifyDiscountDetail> details = dto.getDetails();
            if (CollectionUtils.isNotEmpty(details)) {
                classifyDiscountDetailMapper.deleteByGroupID(dto.getGroupID());
                for (ClassifyDiscountDetail classifyDiscountDetail : details) {
                    classifyDiscountDetail.setId(IdGen.get().nextId());
                    classifyDiscountDetail.setGroupID(dto.getGroupID());
                    classifyDiscountDetail.setCompanyID(SystemContext.getCompanyID());
                }
                classifyDiscountDetailMapper.batchInsert(details);
            }
            classifyDiscountGroupMapper.updateByPrimaryKeySelective(dto);
        }
        return "success";
    }

    private void validateGroupName(ClassifyDiscountGroupDto dto){
        Long groupID = (dto.getGroupID() == null || dto.getGroupID() == 0) ? null : dto.getGroupID();
        Long c = classifyDiscountGroupMapper.countByGroupName(dto.getGroupName(),SystemContext.getCompanyID(),groupID);
        if(c > 0){
            throw new ServiceException("分组已经存在");
        }
    }

    /**
     * 删除分组
     * @param groupID
     * @return
     */
    public Object delete(Long groupID) {
        String countByGroupIDUrl = ProConstants.countByGroupID+groupID;
        DataResult dataResult = HttpUtil.httpGet(countByGroupIDUrl,restTemplate);
        if(!Objects.equal(1,dataResult.getIsSuccess())){
            throw new ServiceException("调用base服务失败");
        }
        if(dataResult.getData() != null){
            String data = (String) dataResult.getData();
            Long a = Longs.tryParse(data);
            if(a>0){
                throw new ServiceException("分组已被使用，不能删除");
            }
        }

        classifyDiscountDetailMapper.deleteByGroupID(groupID);
        classifyDiscountGroupMapper.deleteByPrimaryKey(groupID);
        return "success";
    }

    /**
     * 获取分组详情
     * @param groupID
     * @return
     */
    public Map<String,Object> selectClassifyDiscountGroup(Long groupID) {
        if (groupID == 0) {
            groupID = null;
        }
        List<Map<String, Object>> list = Lists.newArrayList();
        List<JSONObject> bigClassList = getBigClass(groupID);
        for (JSONObject j : bigClassList) {
            String classID = DataUtils.getStr(j, "clazzid");
            List<JSONObject> smallClassList = getSmallClass(classID, groupID);
            Map<String, Object> map = Maps.newHashMap();
            map.put("classfy", j);
            map.put("subClassfy", smallClassList);
            list.add(map);
        }

        ClassifyDiscountGroup classifyDiscountGroup = classifyDiscountGroupMapper.selectByPrimaryKey(groupID);
        Map<String,Object> map = Maps.newHashMap();
        map.put("group",classifyDiscountGroup);
        map.put("details",list);
        return map;
    }

    public Map<String, Object> selectGoodsDiscountGroup(Long groupID) {
       /* List<Map<String,Object>> goods = goodsInfoMapper.selectForB2b();
        List<Map<String,Object>> list =  getNewListForGoods(goods, groupID);*/
        List<Map<String,Object>> list = classifyDiscountDetailMapper.selectGoodsDiscountRate(groupID);
        ClassifyDiscountGroup classifyDiscountGroup = classifyDiscountGroupMapper.selectByPrimaryKey(groupID);
        Map<String,Object> map = Maps.newHashMap();
        map.put("group",classifyDiscountGroup);
        map.put("details",list);
        return map;
    }

    public List<ClassifyDiscountGroup> selectAll(){
        return classifyDiscountGroupMapper.selectAll(SystemContext.getCompanyID());
    }

    public PageInfo<ClassifyDiscountGroup> pageList(int pageNum, int pageSize){
        PageHelper.startPage(pageNum, pageSize);
        List<ClassifyDiscountGroup> list =  classifyDiscountGroupMapper.selectAll(SystemContext.getCompanyID());
        PageInfo<ClassifyDiscountGroup> page = new PageInfo(list);
        return page;
    }

    public ClassifyDiscountGroup selectByPrimaryKey(Long groupID){
        return classifyDiscountGroupMapper.selectByPrimaryKey(groupID);
    }

    /**
     * 获取采购商的大类列表
     * @param userID
     * @return
     */
    public List<JSONObject> getSimpleBigClass(Long userID) {
        //未登录userID为0显示所有分类
        if(Objects.equal(userID,0L)){
            return goodsService.getPlatformClassList(null);
        }
        //非采购商
        Long groupID = getGroupId(userID);
        if(Objects.equal(Constants.exceptGroup,groupID)){
            return goodsService.getPlatformClassList(null);
        }

        List<JSONObject> list = getBigClass(groupID);
        ClassifyDiscountGroup classifyDiscountGroup = classifyDiscountGroupMapper.selectByPrimaryKey(groupID);
        if(classifyDiscountGroup != null && Objects.equal(classifyDiscountGroup.getType(),1)){//按分类
            return getAuthClassFy(list);
        }else if(classifyDiscountGroup != null && Objects.equal(classifyDiscountGroup.getType(),2)){//按商品
            return getAuthClassFyForGoods(list,groupID,1);
        }
        return list;
    }

    /**
     * 获取采购商的小类列表
     * @param clazzId
     * @param userID
     * @return
     */
    public List<JSONObject> getSimpleSmallClass(String clazzId, Long userID) {
        //未登录userID为0显示所有分类
        if(Objects.equal(userID,0L)){
            return goodsService.getClassifyListById(clazzId);
        }
        Long groupID = getGroupId(userID);
        if(Objects.equal(Constants.exceptGroup,groupID)){
            return goodsService.getClassifyListById(clazzId);
        }
        List<JSONObject> list = getSmallClass(clazzId,groupID);
        ClassifyDiscountGroup classifyDiscountGroup = classifyDiscountGroupMapper.selectByPrimaryKey(groupID);
        if(classifyDiscountGroup != null && Objects.equal(classifyDiscountGroup.getType(),1)){//按分类
            return getAuthClassFy(list);
        }else if(classifyDiscountGroup != null && Objects.equal(classifyDiscountGroup.getType(),2)){//按商品
            return getAuthClassFyForGoods(list,groupID,2);
        }
        return list;
    }

    public Object searchBar(GoodsQueryDto goodsQueryDto,Long userID,boolean isCount){
        //未登录userID为0显示所有分类
       /* if(Objects.equal(userID,0L)){
           return isCount ? searchBarCount(goodsQueryDto) : searchBar(goodsQueryDto);
        }
        Long groupID = getGroupId(userID);
        if(Objects.equal(Constants.exceptGroup,groupID)){
            return isCount ? searchBarCount(goodsQueryDto) : searchBar(goodsQueryDto);
        }

        ClassifyDiscountGroup classifyDiscountGroup = classifyDiscountGroupMapper.selectByPrimaryKey(groupID);
        if(classifyDiscountGroup != null && Objects.equal(classifyDiscountGroup.getType(),2)){//按商品
            List<String> goodIds = classifyDiscountDetailMapper.selectGoodIdsByByGroupID(groupID);
            goodsQueryDto.setIds(goodIds);
        }*/
        return isCount ? searchBarCount(goodsQueryDto) : searchBar(goodsQueryDto);
    }



    private  Object searchBar(GoodsQueryDto goodsQueryDto){
        DataResult dataResult = HttpUtil.httpPost(ProConstants.es_goods_searchBar,goodsQueryDto,restTemplate);
        if(!Objects.equal(dataResult.getIsSuccess(),1)){
            throw new ServiceException("搜索服务异常，请稍后重试");
        }
        return dataResult.getData();
    }

    private  Object searchBarCount(GoodsQueryDto goodsQueryDto){
        DataResult dataResult = HttpUtil.httpPost(ProConstants.es_goods_searchBarCount,goodsQueryDto,restTemplate);
        if(!Objects.equal(dataResult.getIsSuccess(),1)){
            throw new ServiceException("搜索服务异常，请稍后重试");
        }
        return dataResult.getData();
    }

     public Object getDiscountRate(Long userID,UserIDGoodsByDto userIDGoodsByDto){
         List<Long> skuIDS = userIDGoodsByDto.getSkuIDS();
         if(CollectionUtils.isEmpty(skuIDS)){
             return Lists.newArrayList();
         }
         List<QueryGoodsSkuRateDto> list = Lists.newArrayList();
         for(Long skuID : skuIDS){
             GoodsSku goodsSku = goodsSkuMapper.selectByPrimaryKey(skuID);
             QueryGoodsSkuRateDto queryGoodsSkuRateDto = new QueryGoodsSkuRateDto();
             queryGoodsSkuRateDto.setSkuID(skuID);

             if(goodsSku == null){
                 /*queryGoodsSkuRateDto.setDiscountRate("1");
                 list.add(queryGoodsSkuRateDto);*/
                 throw new ServiceException("未获取到商品价格信息");
             }else{
                 GoodsInfo goodsInfo = goodsInfoMapper.selectByPrimaryKey(goodsSku.getGoodsID());
                 queryGoodsSkuRateDto.setPrice(goodsSku.getPrice());
                 if(goodsInfo.getPriceType()==1){
                     queryGoodsSkuRateDto.setPrice(goodsService.getTodayGoldPrice(goodsInfo.getSupplierID(),goodsInfo.getAttr(),goodsSku.getAttrJson()));
                 }
                 if(goodsInfo == null){
                     queryGoodsSkuRateDto.setDiscountRate("1");
                     list.add(queryGoodsSkuRateDto);
                 }else{
                     BigDecimal discountRate = getDiscountRate(goodsInfo.getSubClassifyID(),goodsInfo.getGoodsID(),userID);
                     if(discountRate.intValue() == -1) {
                         discountRate = BigDecimal.ONE;
                     }
                     BigDecimal v = BigDecimalUtil.mul(discountRate,BigDecimal.valueOf(100));
                     queryGoodsSkuRateDto.setDiscountRate(String.valueOf(v));
                     list.add(queryGoodsSkuRateDto);
                 }
             }

         }
         return list;

     }

    public int getUserGrade(Long userID) {
        DataResult result = HttpUtil.httpGet(ProConstants.getUserGradeByUserID + userID, restTemplate);
        if (!Objects.equal(result.getIsSuccess(), 1)) {
            throw new ServiceException("未获取到用户等级信息,调用base服务失败");
        }
        if (result.getData() == null) {
            throw new ServiceException("未获用户等级信息");
        }
        int grade = (int) result.getData();
        return grade;

    }

    /**
     * 根据userID获取代理商价格
     */
    public BigDecimal  getSkuPriceByUserGrade(Long userID,Long skuID) {
        GoodsSku goodsSku = goodsSkuMapper.selectByPrimaryKey(skuID);
        BigDecimal price = goodsSku.getPrice();
        int userGrade = getUserGrade(userID);//用户等级  1一级代理  2二级代理  3三级代理  9其它
        QueryGoodsSkuRateDto queryGoodsSkuRateDto = goodsSkuMapper.selectGoodsSkuRateBySkus(skuID,SystemContext.getCompanyID());
        if(queryGoodsSkuRateDto.getPriceType()==1){
            price = goodsService.getTodayGoldPriceByOtherFee(queryGoodsSkuRateDto.getSupplierID(),queryGoodsSkuRateDto.getGoodsAttr(),goodsSku.getAttrJson(),price);
            queryGoodsSkuRateDto.setWholeSalePrice(goodsService.getTodayGoldPrice(queryGoodsSkuRateDto.getSupplierID(),queryGoodsSkuRateDto.getGoodsAttr(),goodsSku.getAttrJson()));
        }
        if(Objects.equal(1,userGrade)){
            if(queryGoodsSkuRateDto.getPriceType()==1){
                price =queryGoodsSkuRateDto.getWholeSalePrice().add(getAgencyAdd(goodsSku.getAttrJson(),queryGoodsSkuRateDto.getViphPrice()));
            }else{
                price =queryGoodsSkuRateDto.getWholeSalePrice().add(queryGoodsSkuRateDto.getWholeSalePrice().multiply(queryGoodsSkuRateDto.getViphPrice().divide(new BigDecimal(1000))));
            }
        }else if(Objects.equal(2,userGrade)){
            if(queryGoodsSkuRateDto.getPriceType()==1){
                price =queryGoodsSkuRateDto.getWholeSalePrice().add(getAgencyAdd(goodsSku.getAttrJson(),queryGoodsSkuRateDto.getVipmPrice()));
            }else{
                price =queryGoodsSkuRateDto.getWholeSalePrice().add(queryGoodsSkuRateDto.getWholeSalePrice().multiply(queryGoodsSkuRateDto.getVipmPrice().divide(new BigDecimal(1000))));
            }

        }else if(Objects.equal(3,userGrade)){
            if(queryGoodsSkuRateDto.getPriceType()==1){
                price =queryGoodsSkuRateDto.getWholeSalePrice().add(getAgencyAdd(goodsSku.getAttrJson(),queryGoodsSkuRateDto.getVipsPrice()));
            }else{
                price =queryGoodsSkuRateDto.getWholeSalePrice().add(queryGoodsSkuRateDto.getWholeSalePrice().multiply(queryGoodsSkuRateDto.getVipsPrice().divide(new BigDecimal(1000))));
            }
        }
        return  price.setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    public BigDecimal getAgencyAdd(String skuAttrJson,BigDecimal val){//获取平台加价
        //(工费*克重)*系数
        Map skuMap = JsonUtil.toMap(skuAttrJson);
        BigDecimal goldWeight = new BigDecimal(null == skuMap.get("weight") ? "0" : skuMap.get("weight").toString());
        BigDecimal craftFeeB = new BigDecimal(null == skuMap.get("wage") ? "0" : skuMap.get("wage").toString());
        BigDecimal fee= craftFeeB.multiply(goldWeight).multiply(val).divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP);
        return  fee;
    }

    /**
     * 获取采购商的折扣
     * @param clazzId
     * @param userID
     * @return
     */
    public BigDecimal getDiscountRate(String clazzId,Long goodsID,Long userID){
        try {
            Map<String,Object> map = getPurchaser(userID);
            Long groupID = MapUtils.getLong(map,"discountGroupID",0L);
            Integer userType = MapUtils.getInteger(map,"userType",0);
            if(userType != 6){//非采购商
                return BigDecimal.valueOf(-1);
            }
            if(groupID == 0){
                return BigDecimal.ONE;
            }

            String id;
            ClassifyDiscountGroup classifyDiscountGroup = classifyDiscountGroupMapper.selectByPrimaryKey(groupID);
            if(classifyDiscountGroup == null){
                logger.info("未获取到分组");
                return BigDecimal.ONE;
            }
            if(Objects.equal(classifyDiscountGroup.getType(),1)){//按分类
                id = clazzId;
            }else{
                id = goodsID+"";
            }
            ClassifyDiscountDetail classifyDiscountDetail = classifyDiscountDetailMapper.selectByGroupIDAndClazzID(groupID,id);
            if(classifyDiscountDetail == null){
                logger.info("未获取到折扣");
                return BigDecimal.ONE;
            }
            return classifyDiscountDetail.getDiscountRate();
        } catch (ServiceException e) {
            e.printStackTrace();
            logger.info(e.getMessage());
            return BigDecimal.ONE;
        }
    }

    private List<JSONObject> getAuthClassFy(List<JSONObject> list) {
        List<JSONObject> cpList = Lists.newArrayList();
        for (JSONObject jsonObject : list) {
            if (!Strings.isNullOrEmpty(DataUtils.getStr(jsonObject, "clazzDiscount"))) {
                Object object = jsonObject.get("clazzDiscount");
                JSONObject jsonObject1 = JSONObject.fromObject(object);
                if (jsonObject1 != null && Objects.equal(DataUtils.getInteger(jsonObject1,"selectAuth"), 0)) {
                    cpList.add(jsonObject);
                }
            }
        }
        return cpList;
    }

    private List<JSONObject> getAuthClassFyForGoods(List<JSONObject> list,Long groupID,Integer level) {
        List<JSONObject> cpList = Lists.newArrayList();
        List<String> goodIds = classifyDiscountDetailMapper.selectGoodIdsByByGroupID(groupID);
        if(CollectionUtils.isEmpty(goodIds)){
            return cpList;
        }
        List<String> classfys;
        if(level == 1){
            classfys = goodsInfoMapper.selectBigClassByGoodIds(goodIds);
        }else {
            classfys = goodsInfoMapper.selectSmallClassByGoodIds(goodIds);
        }

        for(JSONObject jsonObject : list){
            String clazzid = DataUtils.getStr(jsonObject,"clazzid");
            for(String s : classfys){
                if(Objects.equal(s,clazzid)){
                    cpList.add(jsonObject);
                }
            }
        }
        return cpList;
    }

    private Long getGroupId(Long userID) {
        DataResult result = HttpUtil.httpGet(ProConstants.selectPurchaserByUserID + userID, restTemplate);
        if (!Objects.equal(result.getIsSuccess(), 1)) {
            throw new ServiceException("未获取到分类,调用base服务失败");
        }
        if (result.getData() == null) {
            throw new ServiceException("未获取到分类，未获取到采购商信息");
        }
        Map<String, Object> map = (Map<String, Object>) result.getData();
        Integer userType = MapUtils.getInteger(map, "userType");
        if(!Objects.equal(userType,6)){//非采购商返回1000L
            return Constants.exceptGroup;
        }

        Long discountGroupID = MapUtils.getLong(map, "discountGroupID");
        if (discountGroupID == null || discountGroupID == 0) {
            //throw new ServiceException("未获取到分类，未设置采购商的分类权限");
            return Constants.exceptGroup;
        }
        return discountGroupID;
    }

    /**
     *c.companyInfoID,c.type,c.discountGroupID,u.type AS userType
     * @param userID
     * @return
     */
    private Map<String, Object> getPurchaser(Long userID) {
        DataResult result = HttpUtil.httpGet(ProConstants.selectPurchaserByUserID + userID, restTemplate);
        if (!Objects.equal(result.getIsSuccess(), 1)) {
            throw new ServiceException("未获取到采购商信息,调用base服务失败");
        }
        if (result.getData() == null) {
            throw new ServiceException("未获取到采购商信息");
        }
        Map<String, Object> map = (Map<String, Object>) result.getData();
        return map;
    }

    private List<JSONObject> getBigClass(Long groupID) {
       /* JSONObject jsonObject = rest.getForObject(classifyUrl + CommonTools.getExtString(restTemplate, "classifyType"), JSONObject.class);
        if (jsonObject.getInt("isSuccess") != 1) {
            throw new ServiceException("调用云管控服务出错", RestConst.ErrorCode.SERVICE_FAIL);
        }
        List<JSONObject> objectList = jsonObject.getJSONArray("data");*/
        List<JSONObject> objectList = goodsService.getPlatformClassList(null);
        return getNewList(objectList, groupID);
    }

    private List<JSONObject> getSmallClass(String clazzId, Long groupID) {
        /*if (CommonUtils.isEmpty(clazzId)) {
            return null;
        }
        JSONObject jsonObject = rest.getForObject(classifySearchByIdUrl + clazzId, JSONObject.class);
        if (jsonObject.getInt("isSuccess") != 1) {
            throw new ServiceException("调用云管控服务出错", RestConst.ErrorCode.SERVICE_FAIL);
        }
        List<JSONObject> objectList = jsonObject.getJSONArray("data");*/
        List<JSONObject> objectList = goodsService.getClassifyListById(clazzId);
        return getNewList(objectList, groupID);
    }

    /**
     *
     * @param objectList
     * @param groupID
     * @return
     */
    private List<JSONObject> getNewList(List<JSONObject> objectList, Long groupID) {
        List<String> classifyList = new ArrayList<String>();
        for (JSONObject jsonObject1 : objectList) {
            classifyList.add(jsonObject1.get("clazzid") + "");
        }
        if (CollectionUtils.isEmpty(classifyList)) {
            return objectList;
        }

        if(groupID == null || groupID == 0){
            for (JSONObject jsonClazz : objectList) {
                //jsonClazz.remove("clazzVal");
                jsonClazz.put("clazzVal",formatClazzVal(jsonClazz.get("clazzVal")));
                jsonClazz.put("clazzDiscount", "");
            }
            return objectList;
        }
        Map<String, ClassifyDiscountDetail> resultMap = selectByClazzIDList(classifyList, groupID);
        for (JSONObject jsonClazz : objectList) {
            jsonClazz.put("clazzVal",formatClazzVal(jsonClazz.get("clazzVal")));
            //jsonClazz.remove("clazzVal");
            String classID = DataUtils.getStr(jsonClazz, "clazzid");
            if (resultMap.containsKey(classID)) {
                ClassifyDiscountDetail classifyDiscountDetail = resultMap.get(classID);
                if (classifyDiscountDetail != null) {
                    jsonClazz.put("clazzDiscount", classifyDiscountDetail);
                }
            }
            if (!jsonClazz.containsKey("clazzDiscount")) {
                jsonClazz.put("clazzDiscount", "");
            }
        }
        return objectList;
    }

    /**
     * clazzID
     * clazzImage
     * darkImg
     * discountRate
     * employeeVal
     * lightImg
     * subjectID
     * unit
     * val
     * @param clazzVal
     * @return
     */
    private Object formatClazzVal(Object clazzVal){
        JSONObject jsonObject = new JSONObject();
        if(clazzVal == null){
            return "";
        }
        JSONObject j = null;
        try {
            j = JSONObject.fromObject(clazzVal);
        } catch (Exception e) {
            return "";
        }
        jsonObject.put("clazzID",DataUtils.getStr(j,"clazzID",""));
        jsonObject.put("clazzImage",DataUtils.getStr(j,"clazzImage",""));
        jsonObject.put("darkImg",DataUtils.getStr(j,"darkImg",""));
        jsonObject.put("discountRate",DataUtils.getStr(j,"discountRate",""));
        jsonObject.put("employeeVal",DataUtils.getInteger(j,"employeeVal",0));
        jsonObject.put("lightImg",DataUtils.getStr(j,"lightImg",""));
        jsonObject.put("subjectID",DataUtils.getStr(j,"subjectID",""));
        jsonObject.put("unit",DataUtils.getStr(j,"unit",""));
        jsonObject.put("val",DataUtils.getInteger(j,"val",0));
        return jsonObject;
    }


    private List<Map<String,Object>> getNewListForGoods(List<Map<String,Object>> objectList, Long groupID) {
        List<String> classifyList = new ArrayList<String>();
        for (Map jsonObject1 : objectList) {
            classifyList.add(jsonObject1.get("goodsID") + "");
        }
        if (CollectionUtils.isEmpty(classifyList)) {
            return objectList;
        }
        Map<String, ClassifyDiscountDetail> resultMap = selectByClazzIDList(classifyList, groupID);
        for (Map<String,Object> jsonClazz : objectList) {
            String classID = MapUtils.getString(jsonClazz, "goodsID");
            if (resultMap.containsKey(classID)) {
                ClassifyDiscountDetail classifyDiscountDetail = resultMap.get(classID);
                if (classifyDiscountDetail != null) {
                    jsonClazz.put("clazzDiscount", classifyDiscountDetail);
                }
            }
            if (!jsonClazz.containsKey("clazzDiscount")) {
                jsonClazz.put("clazzDiscount", "");
            }
        }
        return objectList;
    }

    private Map<String, ClassifyDiscountDetail> selectByClazzIDList(List<String> classifyList, Long groupID) {
        Map<String, Object> map = Maps.newHashMap();
        map.put("list", classifyList);
        map.put("companyID", SystemContext.getCompanyID());
        if (groupID != null) {
            map.put("groupID", groupID);
        }
        List<ClassifyDiscountDetail> list = classifyDiscountDetailMapper.selectByClazzIDList(map);

        Map<String, ClassifyDiscountDetail> resultMap = Maps.newHashMap();
        for (ClassifyDiscountDetail classifyDiscountDetail : list) {
            resultMap.put(classifyDiscountDetail.getClazzID(), classifyDiscountDetail);
        }
        return resultMap;
    }

    public String getClassifySearchByIdUrl() {
        return classifySearchByIdUrl;
    }

    public void setClassifySearchByIdUrl(String classifySearchByIdUrl) {
        this.classifySearchByIdUrl = classifySearchByIdUrl;
    }

    public String getClassifyUrl() {
        return classifyUrl;
    }

    public void setClassifyUrl(String classifyUrl) {
        this.classifyUrl = classifyUrl;
    }
}
